<template>
  <div style="margin-top: 20px">
    <ko-card :title="$t('business.configuration.certificate')">
      <el-form ref="form" label-position="top" :model="editForm" :rules="rules">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item
              :label="$t('business.configuration.publicKey')"
              prop="publicKey"
              required
            >
              <ko-data-item
                v-model="editForm.publicKey"
                itemType="textarea"
                class="w-full"
                :rows="5"
                @change="syncToModel"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('business.configuration.privateKey')"
              prop="privateKey"
              required
            >
              <ko-data-item
                v-model="editForm.privateKey"
                class="w-full"
                itemType="textarea"
                :rows="5"
                @change="syncToModel"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </ko-card>
  </div>
</template>

<script setup lang="ts">
import KoCard from "@/views/domain/kubeHud/views/components/ko-card/index.vue";
import KoDataItem from "@/views/domain/kubeHud/views/components/ko-data-item/index.vue";
import { onMounted, ref } from "vue";
import { SecretDataKey } from "../../../api/k8s";
import { useFormRule } from "../../../utils/rules";
import { decodeFromBase64, encodeToBase64 } from "@/utils/text";
const { RequiredRule } = useFormRule();

type Prop = {
  dataObj: Object;
};

const props = defineProps<Prop>();
const emit = defineEmits(["update:dataObj"]);
const formRef = ref();
const editForm = ref({
  privateKey: "",
  publicKey: ""
});

const rules = {
  publicKey: [RequiredRule]
};

const parseToForm = () => {
  if (props.dataObj && Object.keys(props.dataObj).length > 0) {
    if (props.dataObj[SecretDataKey.Privatekey]) {
      editForm.value.privateKey = decodeFromBase64(
        props.dataObj[SecretDataKey.Privatekey]
      );
    }
    if (props.dataObj[SecretDataKey.Publickey]) {
      editForm.value.publicKey = decodeFromBase64(
        props.dataObj[SecretDataKey.Publickey]
      );
    }
  }
};

const syncToModel = () => {
  formRef.value?.validate(validate => {
    if (validate) {
      emit("update:dataObj", {
        [SecretDataKey.Privatekey]: encodeToBase64(editForm.value.privateKey),
        [SecretDataKey.Publickey]: encodeToBase64(editForm.value.publicKey)
      });
    }
  });
};

onMounted(() => {
  parseToForm();
});
</script>

<style scoped></style>
